package user

import (
	"errors"
	"fmt"
	"io"
	"net/http"

	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/svc"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/tool"
	"gitee.com/liuxuezhan/ar-platform/admin-api/internal/types"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/common"
	"gitee.com/liuxuezhan/ar-platform/admin-api/pkg/excel"

	"gitee.com/liuxuezhan/ar-platform/base-common/result"
	"gitee.com/liuxuezhan/ar-platform/rpc-client/userServiceClient/userrpc"
	"github.com/zeromicro/go-zero/rest/httpx"
)

// 会员管理 - 会员层级 - 导出
func UserLevelExportHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.UserLevelExportRequest
		if err := httpx.Parse(r, &req); err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		rpcReq := &userrpc.UserLevelSearchRequest{
			Id:                req.Id,
			AgentLevel:        req.AgentLevel,
			Level:             req.Level,
			RegisterTimeStart: req.RegisterTimeStart,
			RegisterTimeEnd:   req.RegisterTimeEnd,
		}
		client := svcCtx.UserServiceRPC
		stream, err := client.UserLevelExport(r.Context(), rpcReq)
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}

		excelWriter, err := excel.NewExcelWriter()
		if err != nil {
			result.HttpErrorResult(r.Context(), w, err)
			return
		}
		defer excelWriter.Close()

		excelWriter.SetHeaders([]string{
			"会员ID",
			"账号",
			"上级ID",
			"层级",
			"直属下级",
			"全部下级",
			"代理",
			"注册时间",
			"下单（金额/次/人）",
			"中奖（金额/次/人）",
			"佣金",
			"充值（金额/次/人）",
			"提现（金额/次/人）",
			"红包",
			"签到",
			"代理红包",
			"充值赠送",
			"注册送金",
			"彩金充值",
			"首充满赠送",
		})
		index := 2
		for {
			data, err := stream.Recv()
			if errors.Is(err, io.EOF) {
				break
			}
			if err != nil {
				result.HttpErrorResult(r.Context(), w, err)
				return
			}

			t1 := fmt.Sprintf("%.2f/%d/%d", data.BetAmount, data.BetCount, data.BetUserCount)
			t2 := fmt.Sprintf("%.2f/%d/%d", data.WinAmount, data.WinCount, data.WinUserCount)
			t3 := fmt.Sprintf("%.2f/%d/%d", data.RechargeAmount, data.RechargeCount, data.RechargeUserCount)
			t4 := fmt.Sprintf("%.2f/%d/%d", data.WithdrawAmount, data.WithdrawCount, data.WithdrawUserCount)
			excelWriter.AddRow(index, []interface{}{
				data.Id,
				data.Account,
				data.ParentId,
				data.Level,
				data.ChildNum,
				data.AllChildNum,
				common.EnumUserAgentLevel[data.AgentLevel],
				tool.TimeFormat(data.RegistAt, ""),
				t1,
				t2,
				data.BrokerAmount,
				t3,
				t4,
				data.RedAmount,
				data.SinginAmount,
				data.AgentRedAmount,
				data.RechargeGiftAmount,
				data.RegistGiftAmount,
				data.BetRechargeAmount,
				data.FirstRechargeFullGiftAmount,
			})
			index++
		}

		excelWriter.Flush()

		// download
		w.Header().Set("Content-Type", "application/octet-stream")
		w.Header().Set("Content-Disposition", "attachment; filename=users.xlsx")
		excelWriter.Write(w)
	}
}
